package OrderService

import (
	"fmt"
	"gdshop-back-end-go/client-api/app/response/CartResp"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/service-other/GoodsActivityService"
	"github.com/gogf/gf/util/gconv"
	"strconv"
)

// 针对购物车的，计算活动的
func GoodsActivityByCartModel(carts []*CartResp.Details, activityNow *entity.GoodsActivity) (int64, error) {
	var totalPrice int64 = 0
	// 先计算 当前分组全部总价
	for _, item := range carts {
		totalPrice += item.Paid
	}

	fmt.Println("总价 ", totalPrice)
	// 计算出总的优惠价
	_, discountMoney, err := GoodsActivityService.GetMaxDiscountActivity([]*entity.GoodsActivity{
		activityNow,
	}, totalPrice)
	if err != nil {
		return 0, err
	}

	fmt.Println("总的优惠价 ", discountMoney)

	// 保持一致性优惠
	var discountMoney2 int64 = 0
	// 分摊到商品上面
	for _, item := range carts {
		tmpMoney := float64(item.Paid) / float64(totalPrice) * float64(discountMoney)
		discountMoney2 += gconv.Int64(strconv.FormatFloat(tmpMoney, 'f', 0, 64))
		item.Paid = item.Paid - gconv.Int64(strconv.FormatFloat(tmpMoney, 'f', 0, 64))
	}

	// 矫正优惠
	if discountMoney2 > discountMoney {
		// 多了
		carts[0].Paid -= discountMoney2 - discountMoney
	}
	// 少了
	if discountMoney > discountMoney2 {
		carts[0].Paid -= discountMoney - discountMoney2
	}

	return discountMoney, nil
}
